package com.rop.znyx.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.*;
import org.apache.commons.lang.StringUtils;

import java.util.Date;

/**
 * Created with IntelliJ IDEA
 * User: Rop
 * Date: 2023/7/18
 * Time: 9:22
 * Description:
 */
public class JwtHelper {
    private static final Long tokenExpireTime = 365L * 24 * 60 * 60 * 1000;

    private static final String tokenSignKey = "ZNYX";

    public static String createToken(Long userId, String username) {
        return Jwts.builder()
                .setSubject("ZNYX_USER")
                .setExpiration(new Date(java.lang.System.currentTimeMillis() + tokenExpireTime))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public static Long getUserId(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims body = claimsJws.getBody();

        Integer userId = Convert.toInt(body.get("userId"));
        return userId.longValue();
    }

    public static String getUsername(String token) {
        if (StrUtil.isBlank(token)) {
            return "";
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims body = claimsJws.getBody();

        return Convert.toStr(body.get("username"));
    }

    public static void removeToken(String token) {
        // jwtToken可以直接在客户端丢弃
    }

    public static void main(String[] args) {
        String token = createToken(1L, "rop");

        System.err.println(token);
        System.err.println(getUserId(token));
        System.err.println(getUsername(token));
    }
}
